package com.example.jsoup.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.example.jsoup.util.ProxyUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class CsdnService {

    private ProxyUtil proxyUtil;
    private RedissonClient redissonClient;
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    public CsdnService(RedissonClient redissonClient,ProxyUtil proxyUtil) {

        this.redissonClient = redissonClient;
        this.proxyUtil = proxyUtil;
        this.threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        this.threadPoolTaskScheduler.setPoolSize(100);
        this.threadPoolTaskScheduler.setThreadNamePrefix("csndThread-");
        this.threadPoolTaskScheduler.initialize();
    }

    @Scheduled(cron = "0 1 0 * * ?")
    public void createTask() throws IOException {
        Document doc = Jsoup.connect("https://blog.csdn.net/u012796085?spm=1011.2124.3001.5343&type=blog")
                .header("user-agent",proxyUtil.getAgent())
//                .proxy(proxyUtil.getproxy())
                .get();
        Elements likeItemAll = doc.select(".navList-box .blog-list-box a");
        //爬取文章列表
        List<String> articleList = new ArrayList<>();
        for (Element element : likeItemAll) {
            String urlStr = element.attr("href");
            String title = element.selectFirst("h4").text();
            articleList.add(title + "AAA" + urlStr);
            if(articleList.size()>80)break;
        }
        //取随机文章设置200条随机定时任务
        long artNum = articleList.size();
        for (int i = 0; i < 300; i++) {
            String[] a = articleList.get(RandomUtil.randomInt(0, (int) artNum)).split("AAA");
            Task task = new Task(a[1], redissonClient,proxyUtil);
            //一天24小时随机分布执行任务时间
            threadPoolTaskScheduler.schedule(task, RandomUtil.randomDate(new Date(), DateField.MINUTE, 1, 1440));
        }
        log.info("任务已创建");
    }

    public static class Task implements Runnable {

        private String url;
        private RedissonClient redissonClient;
        private ProxyUtil proxyUtil;

        public Task(String url,  RedissonClient redissonClient,ProxyUtil proxyUtil) {
            this.url = url;
            this.proxyUtil = proxyUtil;
            this.redissonClient = redissonClient;
        }

        @Override
        public void run() {
            try {
                String[] proxyStr = proxyUtil.getproxy().split(":");
                Document doc = Jsoup.connect(url)
                        .header("user-agent",proxyUtil.getAgent())
//                        .proxy(proxyStr[0],Integer.parseInt(proxyStr[1]))
                        .timeout(10000)
                        .get();
                System.out.println(doc.body().selectFirst("h1").text());
                String runDay = DateUtil.format(new Date(), "yyyy-MM-dd");
                RAtomicLong redisLong = redissonClient.getAtomicLong(runDay);
                redisLong.incrementAndGet();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
